package com.chianghao.nio.core.handle;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author ChiangHao
 * @date 2022/10/18 21:33
 */
public class ChannelWriteThread implements Runnable{


    private SelectionKey key;
    private SocketChannel channel;

    public ChannelWriteThread(SelectionKey key, SocketChannel channel){
        this.key = key;
        this.channel = channel;
    }

    @Override
    public void run() {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {

            ChannelContext channelContext = null;
            if(key.attachment()!=null){
                channelContext = (ChannelContext)key.attachment();
                buffer.put(channelContext.getResponse().getHttpContent().getBytes(StandardCharsets.UTF_8));
            }else{
                buffer.put("".getBytes(StandardCharsets.UTF_8));
            }
            buffer.flip();
            channel.write(buffer);
            buffer.clear();
            closeChannel(channel);
            key.cancel();
        } catch (Throwable e) {
            e.printStackTrace();
            closeChannel(channel);
            key.cancel();
        }
    }

    private static void closeChannel(SocketChannel channel) {
        if (channel == null) {
            return;
        }
        Socket socket = channel.socket();
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
